<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex(){
		$criteria=new CDbCriteria();
        $criteria->condition = 'is_lock = :is_lock AND is_delete = :is_delete';
        $criteria->params = array(
            ':is_lock'=>0,
            ':is_delete'=>0
        );
        $criteria->order = 'create_date DESC';
        $count = Blog::model()->count($criteria);
        $pages=new CPagination($count);

        // results per page
        $pages->pageSize=10;
        $pages->applyLimit($criteria);
        $models = Blog::model()->findAll($criteria);
        
        $this->render('index', array(
            'models' => $models,
            'pages' => $pages
        ));
	}
	
	/**
	 * Feed列表
	 */
	public function actionFeed(){
		$criteria=new CDbCriteria();
		$criteria->condition = 'is_lock = :is_lock AND is_delete = :is_delete';
		$criteria->order = 'create_date DESC';
		$criteria->limit = 50;
		$criteria->offset = 0;
        $criteria->params = array(
            ':is_lock'=>0,
            ':is_delete'=>0
        );
		$models = Blog::model()->findAll($criteria);

		//rss创建
		$rss = new Rss("GoWhich|项目问题大集合",Yii::app()->request->hostInfo, Yii::app()->params['description']);
		$rss->setWebMaster(Yii::app()->params['email']);
		$rss->setAuthor("Durban");
		foreach($models as $key=>$value){
			$rss->addItem(
					$value->title,
					Yii::app()->createAbsoluteUrl('site/view',array('id'=>$value->id)),
					$value->description,
					date('r',strtotime($value->create_date)),
					Yii::app()->createAbsoluteUrl('site/view',array('id'=>$value->id))
					);
		}

		$this->render('feed',array('rss'=>$rss->show()));
	}

    /**
     * sitemap列表
     */
    public function actionSitemap(){

        //rss创建
        $obj = new Sitemap();

        $this->render('sitemap',array('rss'=>$obj->show()));
    }

    public function actionSitemapXsl(){
        $this->render('sitemapxsl');
    }


	/**
	 * Tag 标签分类
	 */
    public function actionTag($tag){
        $tag = htmlspecialchars($tag);
        $tag = preg_replace('$#dotted#$','.',urldecode($tag)); 
        $tag = mysql_escape_string($tag);
        $tag = addcslashes($tag, '%_');
        $criteria=new CDbCriteria();
        $criteria->condition = "tag LIKE :tag";
        $criteria->params =array(':tag'=>"%{$tag}%");
        $criteria->order = 'create_date DESC';
        $count = Blog::model()->count($criteria);
        $pages=new CPagination($count);

        // results per page
        $pages->pageSize=10;
        $pages->applyLimit($criteria);
        $models = Blog::model()->findAll($criteria);
        
        $this->render('tag', array(
            'models' => $models,
            'pages' => $pages,
            'tag'=>$tag
        ));
        
    }
    
    public function actionCategory($category){
        $category = urldecode($category);
        $category = CHtml::encode($category);
        $category = mysql_escape_string($category);
        $category = addcslashes($category, '%_');
        
        $typeId = $this->loadTypeId($category);
        
        $criteria=new CDbCriteria();
        if(!empty($typeId)){
            $criteria->condition = "type_id LIKE :type_id";
            $criteria->params =array(':type_id'=>$typeId);
            $criteria->order = 'create_date DESC';
            $count = Blog::model()->count($criteria);
            $pages=new CPagination($count);

            // results per page
            $pages->pageSize=10;
            $pages->applyLimit($criteria);
            $models = Blog::model()->findAll($criteria);
        }else{
            $models = '';
            $pages = '';
        }
        
        $this->render('category', array(
            'models' => $models,
            'pages' => $pages,
            'category'=>$category
        ));
    }

    public function getMictime(){
        $startMictime = explode(' ',microtime());
        return $startMictime[1].$startMictime[0];
    }
    
    /**
     * 文章搜索
     * @param type $keyword
     * @param type $where
     */
    public function actionSearch(){
        $startMictime = $this->getMictime();

        $type =  Yii::app()->request->getParam('type','');
        $key = Yii::app()->request->getParam('key','');
        $key = trim($key);
        $key = strip_tags($key);
        $key = $this->filterSafe($key);
        
        if($type == 'google'){
            $this->render('googlesearch');
        }else{ 
            $keyword = mysql_escape_string($key);
            if(!empty($keyword)){
                $keywordArr = preg_split("# #i", $keyword);
                $criteria=new CDbCriteria();
                foreach ($keywordArr as $key=>$value){
                    $criteria->addSearchCondition('title', $value, true, 'OR');
                }
                foreach ($keywordArr as $key=>$value){
                    $criteria->addSearchCondition('description', $value, true, 'OR');
                }
                // foreach ($keywordArr as $key=>$value){
//                     $criteria->addSearchCondition('tag', $value, true, 'Like');
//                 }

                $criteria->order = 'create_date DESC';

                $count = Blog::model()->count($criteria);
                $pages=new CPagination($count);

                // results per page
                $pages->pageSize=10;
                $pages->applyLimit($criteria);
                $models = Blog::model()->findAll($criteria);

                $this->render('search', array(
                    'models' => $models,
                    'pages' => $pages,
                    'keyword'=>$keyword,
                    'keywordArr'=>$keywordArr,
                    'lengthMictime'=>$this->getMictime() - $startMictime,
                ));

            }else{
                $this->render('search',array(
                    'keyword'=>$keyword,
                    'lengthMictime'=>$this->getMictime() - $startMictime,
                )); 
            }
        }
    }

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError(){
		if($error=Yii::app()->errorHandler->error){
            if($error['code'] == 404){
                $this->render('error404', $error);
                exit;
            }
            if($error['code'] == 403){
                $this->render('error403', $error);
                exit;
            }
            if($error['code'] == 400){
                $this->render('error400', $error);
                exit;
            }
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}
    
    

	/**
	 * Displays the contact page
	 */
//	public function actionContact()
//	{
//		$model=new ContactForm;
//		if(isset($_POST['ContactForm']))
//		{
//			$model->attributes=$_POST['ContactForm'];
//			if($model->validate())
//			{
//				$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
//				$subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
//				$headers="From: $name <{$model->email}>\r\n".
//					"Reply-To: {$model->email}\r\n".
//					"MIME-Version: 1.0\r\n".
//					"Content-type: text/plain; charset=UTF-8";
//
//				mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
//				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
//				$this->refresh();
//			}
//		}
//		$this->render('contact',array('model'=>$model));
//	}

	/**
	 * Displays the login page
	 */
//	public function actionLogin()
//	{
//		$model=new LoginForm;
//
//		// if it is ajax validation request
//		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
//		{
//			echo CActiveForm::validate($model);
//			Yii::app()->end();
//		}
//
//		// collect user input data
//		if(isset($_POST['LoginForm']))
//		{
//			$model->attributes=$_POST['LoginForm'];
//			// validate user input and redirect to the previous page if valid
//			if($model->validate() && $model->login())
//				$this->redirect(Yii::app()->user->returnUrl);
//		}
//		// display the login form
//		$this->render('login',array('model'=>$model));
//	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
//	public function actionLogout()
//	{
//		Yii::app()->user->logout();
//		$this->redirect(Yii::app()->homeUrl);
//	}
    
    public function actionView($id){
        $model=Blog::model()->findByPk($id);
        if($model===null){
            throw new CHttpException(404,'请求的页面不存在.');
        }
        $this->blogClick($id);
        $prev = $this->viewPrev($id);
        $next = $this->viewNext($id);
			
        $this->render('view',array(
            'model'=>$model,
            'prev'=>$prev,
            'next'=>$next,
                )
                );
    }
    
    
    public function viewPrev($id){
        $criteria=new CDbCriteria;
        $criteria->order='id DESC';
        $criteria->condition="id<:id";
        $criteria->params=array(':id'=>$id);
        return Blog::model()->find($criteria);
    }

    public function viewNext($id){
        $criteria=new CDbCriteria;
        $criteria->order='id ASC';
        $criteria->condition="id>:id";
        $criteria->params=array(':id'=>$id);
        return Blog::model()->find($criteria);
    }
    
    public function loadTypeId($category){
        $criteria=new CDbCriteria();
        $criteria->condition = "name = :name AND category = 'blog'";
        $criteria->params = array(':name'=>$category);
        
        $typeObj = Type::model()->findAll($criteria);
        if(!empty($typeObj)){
            foreach($typeObj as $k=>$v){
                return $v->id;
            }
        }
    }
    
    /**
     * 文章点击浏览量
     * @param type $id
     */
    public function blogClick($id){
        $model=$this->loadBlogModel($id);
        $model->read_sum += 1;
        $model->save();
    }
    
    
    public function loadBlogModel($id){
		$model=Blog::model()->findByPk($id);
        if($model===null){
            return null;
        }else{
            return $model;
        }
	}
	
	/**
	 * 搜索关键字过滤
	 * @param unknown $str
	 * @return mixed
	 */
	private function filterSafe($str){
		$str=preg_replace("/\s+/", "", $str); //过滤多余回车
		$str=preg_replace("/<[ ]+/si","",$str); //过滤<__("<"号后面带空格)
		
		$str=preg_replace("/<\!--.*?-->/si","",$str); //注释
		$str=preg_replace("/<(\!.*?)>/si","",$str); //过滤DOCTYPE
		$str=preg_replace("/<(\/?html.*?)>/si","",$str); //过滤html标签
		$str=preg_replace("/<(\/?head.*?)>/si","",$str); //过滤head标签
		$str=preg_replace("/<(\/?meta.*?)>/si","",$str); //过滤meta标签
		$str=preg_replace("/<(\/?body.*?)>/si","",$str); //过滤body标签
		$str=preg_replace("/<(\/?link.*?)>/si","",$str); //过滤link标签
		$str=preg_replace("/<(\/?form.*?)>/si","",$str); //过滤form标签
		$str=preg_replace("/cookie/si","COOKIE",$str); //过滤COOKIE标签
		
		$str=preg_replace("/<(applet.*?)>(.*?)<(\/applet.*?)>/si","",$str); //过滤applet标签
		$str=preg_replace("/<(\/?applet.*?)>/si","",$str); //过滤applet标签
		
		$str=preg_replace("/<(style.*?)>(.*?)<(\/style.*?)>/si","",$str); //过滤style标签
		$str=preg_replace("/<(\/?style.*?)>/si","",$str); //过滤style标签
		
		$str=preg_replace("/<(title.*?)>(.*?)<(\/title.*?)>/si","",$str); //过滤title标签
		$str=preg_replace("/<(\/?title.*?)>/si","",$str); //过滤title标签
		
		$str=preg_replace("/<(object.*?)>(.*?)<(\/object.*?)>/si","",$str); //过滤object标签
		$str=preg_replace("/<(\/?objec.*?)>/si","",$str); //过滤object标签
		
		$str=preg_replace("/<(noframes.*?)>(.*?)<(\/noframes.*?)>/si","",$str); //过滤noframes标签
		$str=preg_replace("/<(\/?noframes.*?)>/si","",$str); //过滤noframes标签
		
		$str=preg_replace("/<(i?frame.*?)>(.*?)<(\/i?frame.*?)>/si","",$str); //过滤frame标签
		$str=preg_replace("/<(\/?i?frame.*?)>/si","",$str); //过滤frame标签
		
		$str=preg_replace("/<(script.*?)>(.*?)<(\/script.*?)>/si","",$str); //过滤script标签
		$str=preg_replace("/<(\/?script.*?)>/si","",$str); //过滤script标签
		$str=preg_replace("/javascript/si","Javascript",$str); //过滤script标签
		$str=preg_replace("/vbscript/si","Vbscript",$str); //过滤script标签
		$str=preg_replace("/on([a-z]+)\s*=/si","",$str); //过滤script标签
		$str=preg_replace("/&#/si","",$str); //过滤script标签，如javAsCript:alert(﻿
		$str=preg_replace("#\"|\'|\>#si","",$str);
		
		return $str;
	}
    
    
}
